import { Card, Flex, Input, Button, Table, Space, Modal, notification, Pagination } from "antd";
import { useEffect, useState } from "react";
import {
  getTips as getTipsApi,
  addTip as addTipApi,
  deleteTip as deleteTipApi,
  editTip as editTipApi,
} from "../../request/api/todoList";
import to from "await-to-js";
// 引入mock的json-server数据，以便于分页时候拿到Tips的总数
import db from "../../../db.json";
// 引入防抖函数
import debounce from "../../utils/debounce";
// todoList组件
const Index = () => {
  // 弹出提示框
  const [api, contextHolder] = notification.useNotification();
  useEffect(() => {
    getTips();
    console.log(db.tips.length);
    setTotal(db.tips.length);
  }, []);
  // 拿到模拟数据的数量
  const [total, setTotal] = useState(db.tips.length);
  // 搜索框防抖处理
  const handleInputChange = debounce(async (e) => {
    // 因为json-server无法实现模糊查询，我这里直接把所有数据请求过来再手动模糊筛选，模拟模糊查询的流程
    setGetTipsListParams({
      title: "",
      // 模拟分页的查询参数
      _start: 0,
      _end: 10,
      _sort: "id",
      _order: "desc",
    });
    const [err, res] = await to(getTipsApi(getTipsListParams));
    if (!err) {
      let titleReg = new RegExp(e.target.value);
      setListData((listData) => {
        listData = res.filter((item) => {
          console.log(item.title.match(titleReg));
          return item.title.match(titleReg);
        });
        console.log(listData);
        return listData;
      });
    }
  }, 500);
  //   列表数据
  const [listData, setListData] = useState([]);
  //   获取列表的参数
  const [getTipsListParams, setGetTipsListParams] = useState({
    // 因为用的json-server，就只能按照json-server的格式传递参数
    // 模拟模糊查询参数
    title: "",
    // 模拟分页的查询参数
    _start: 0,
    _end: 10,
    _sort: "id",
    _order: "desc",
  });
  //   切换页数回调
  const onPageChange = (pageNumber) => {
    setGetTipsListParams((getTipsListParams) => {
      getTipsListParams._end = 10 * pageNumber;
      getTipsListParams._start = getTipsListParams._end - 10;
      getTips();
      return getTipsListParams;
    });
  };
  //  获取列表api
  const getTips = async () => {
    const [err, res] = await to(getTipsApi(getTipsListParams));
    if (!err) {
      setListData(res);
    }
  };
  //   控制批量删除按钮状态
  const [multiple, setMultiple] = useState(true);
  //   单个删除按钮
  const handleDelete = async (item) => {
    const [err] = await to(deleteTipApi(item.id));
    if (!err) {
      setIsModalOpen(false);
      api["success"]({
        message: "删除成功",
      });
      getTips();
    }
  };
  // 批量删除按钮
  const handleDeletes = async () => {
    console.log(mySelectedRows);
    // 因为json-server模拟的后端环境不能实现批量删除，直接通过前端循环删除来模拟一下业务场景
    for (let i = 0; i < mySelectedRows.length; i++) {
      const [err] = await to(deleteTipApi(mySelectedRows[i].id));
      if (err) {
        api["error"]({
          message: "删除失败",
        });
      }
    }
    api["success"]({
      message: "删除成功",
    });
    setTotal(db.tips.length);
    getTips();
    setMultiple(true)
  };
  const [isAdd, setIsAdd] = useState(false);
  // 点击编辑按钮
  const handleEdit = (item) => {
    // 设置编辑庄涛
    setIsAdd(false);
    // 获取当前节点数据
    setAddParams(item);
    // 开启弹窗
    setIsModalOpen(true);
  };
  //   确定修改按钮
  const handleEditTip = async () => {
    const [err] = await to(editTipApi(addParams));
    if (err) {
      api["error"]({
        message: "删除失败",
      });
    } else {
      api["success"]({
        message: "修改成功",
      });
    }
    setIsModalOpen(false);
    getTips();
  };
  //   点击新增按钮
  const handleAdd = () => {
    setAddParams({});
    setIsAdd(true);
    setIsModalOpen(true);
  };
  //   新增参数
  const [addParams, setAddParams] = useState({});
  //   控制新增弹框状态
  const [isModalOpen, setIsModalOpen] = useState(false);
  //   确定新增按钮
  const handleOk = async () => {
    const [err] = await to(addTipApi(addParams));
    if (!err) {
      setIsModalOpen(false);
      api["success"]({
        message: "新增成功",
      });
      getTips();
    } else {
      console.log(err);
    }
  };
  //   关闭弹窗按钮
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const columns = [
    {
      title: "事项",
      dataIndex: "title",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => handleEdit(record)}>编辑</a>
          <a onClick={() => handleDelete(record)}>删除</a>
        </Space>
      ),
    },
  ];
  //   保存勾选的数据
  const [mySelectedRows, setSelectedRows] = useState([]);
  //   配置勾选
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedRows((mySelectedRows) => {
        mySelectedRows = selectedRows;
        if (mySelectedRows.length === 0) {
          setMultiple(true);
        } else {
          setMultiple(false);
        }
        return mySelectedRows;
      });
      //   console.log(mySelectedRows);
    },
  };
  return (
    <>
      {contextHolder}
      <Card style={{ width: 800, margin: "0vh auto" }}>
        <Flex gap="middle">
          <Button type="primary" htmlType="submit" onClick={() => handleAdd()}>
            新增
          </Button>
          <Button type="primary" disabled={multiple} danger htmlType="submit" onClick={() => handleDeletes()}>
            删除
          </Button>
          <Input
            //   style={{margin}}
            className="mb-20px"
            onChange={(e) => handleInputChange(e)}
            placeholder="请输入要查询的事项"
            // enterButton="筛选"
            size="large"
            // onSearch={onSearch}
          />
        </Flex>
        <div>
          <Table pagination={false} rowSelection={rowSelection} columns={columns} dataSource={listData} />
          {total && <Pagination showQuickJumper defaultCurrent={1} total={total} onChange={onPageChange} />}
        </div>
      </Card>
      <div></div>
      {/* 新增/编辑弹窗 */}
      <Modal centered open={isModalOpen} onOk={handleOk} onCancel={handleCancel} footer={false}>
        <div style={{ textAlign: "center", margin: "10px 0", fontSize: "16px", fontWeight: "600" }}>
          {isAdd ? "新增事项" : "修改事项"}
        </div>
        <Flex style={{ margin: "10px 0" }}>
          <div className="w-15%">事项名：</div>{" "}
          <Input
            value={addParams.title}
            onChange={(e) => {
              if (!addParams.id) {
                // 如果没有id则为新增
                //   模拟后端生成一个随机key和id
                const key = Math.random().toString(36).slice(2);
                setAddParams({ title: e.target.value, key });
              } else {
                // 已有id为编辑
                setAddParams({ title: e.target.value, id: addParams.id, key: addParams.key });
              }
            }}
          />
        </Flex>
        <Flex justify={"flex-end"}>
          {isAdd ? (
            <Button type={"primary"} onClick={handleOk}>
              确定
            </Button>
          ) : (
            <Button type={"primary"} onClick={handleEditTip}>
              修改
            </Button>
          )}
        </Flex>
      </Modal>
    </>
  );
};

export default Index;
